import { defineStore } from 'pinia'

interface TodoItem {
  id: number
  text: string
  completed: boolean
}

export const useTodoStore = defineStore('todo', {
  state: () => ({
    todos: JSON.parse(localStorage.getItem('todos') || '[]') as TodoItem[]
  }),

  actions: {
    addTodo(text: string) {
      const newTodo = {
        id: Date.now(),
        text,
        completed: false
      }
      this.todos.push(newTodo)
      this.saveToLocalStorage()
    },

    toggleTodo(id: number) {
      const todo = this.todos.find(todo => todo.id === id)
      if (todo) {
        todo.completed = !todo.completed
        this.saveToLocalStorage()
      }
    },

    deleteTodo(id: number) {
      this.todos = this.todos.filter(todo => todo.id !== id)
      this.saveToLocalStorage()
    },

    saveToLocalStorage() {
      localStorage.setItem('todos', JSON.stringify(this.todos))
    }
  },

  getters: {
    completedTodos: (state) => state.todos.filter(todo => todo.completed),
    activeTodos: (state) => state.todos.filter(todo => !todo.completed)
  }
}) 